<template>
    <avue-crud :data="tableData"
               @refresh-change="refreshChange"
               :page="pageSearch"
               @size-change="sizeChange"
               @current-change="currentChange"
               :option="option"
               @expand-change="expandChanges">
        <template #menu-left>
            <add-button text="新增任务" @click="handleAdd" style="background-color: #3cc393"/>
            <export-button/>
            <import-button/>
        </template>
        <template #menu="scope">
            <text-add-button  :text="scope.row.ktrJsonId?'流程编辑':'流程设计'" @click="handleFlow(scope.row)"/>
            <text-button text="查看" @click="handleView(scope, row)"/>
            <text-edit-button @click="handleUpdate(scope.row)"/>
            <text-delete-button
                @click="handleDelete(scope.row)"
                :title="'是否确认删除' + scope.row.cateName + '?'"
            />
            <el-dropdown class="ml10" @command="(command) => handleMore(command, scope.row)">
                <span class="el-dropdown-link text-navy">
                  更多<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item
                            command="start"
                            v-if="scope.row.type === '1' && scope.row.jobInfoDTO?.triggerStatus === '0'"
                        >启动</el-dropdown-item>
                        <el-dropdown-item
                            command="stop"
                            v-if="scope.row.type === '1' && scope.row.jobInfoDTO?.triggerStatus === '1'"
                        >停止</el-dropdown-item>
                        <el-dropdown-item
                            command="trigger"
                            v-if="scope.row.type === '1'"
                        >执行一次</el-dropdown-item>
                        <el-dropdown-item
                            command="triggerStart"
                            v-if="scope.row.type === '2' && scope.row.status === '0'"
                        >启动</el-dropdown-item>
                        <el-dropdown-item
                            command="triggerStop"
                            v-if="scope.row.type === '2' && scope.row.status === '1'"
                        >停止</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>

        </template>
        <template #status="scope">
<!--            <span :class="scope.row.jobInfoDTO?.triggerStatus === '0' ? 'text-danger' : ''">{{-->
<!--                    selectDictLabel(statusOptions, scope.row.type === '1' ? scope.row.jobInfoDTO?.triggerStatus : scope.row.status)-->
<!--                }}</span>-->
            <span>
                  <el-tag
                      v-if="(scope.row.type === '1' ? scope.row.jobInfoDTO?.triggerStatus : scope.row.status) === '1'"
                      type="success"
                  >{{ selectDictLabel(statusOptions, scope.row.type === '1' ? scope.row.jobInfoDTO?.triggerStatus : scope.row.status) }}
                  </el-tag>
                  <el-tag v-else type="danger">{{
                      selectDictLabel(statusOptions, scope.row.type === '1' ? scope.row.jobInfoDTO?.triggerStatus : scope.row.status)
                    }}</el-tag>
                </span>
        </template>
        <template #type="scope">
                <span>{{
                    scope.row.type === '1' ? '离线任务' : '实时任务'
                  }}</span>
        </template>
        <template #runMode="scope">
<!--            <span>{{-->
<!--                    scope.row.runMode === '2' ? scope.row.jobInfoDTO.jobCron : scope.row.runMode === '1' ? '手动运行' : '禁用'-->
<!--                }}</span>-->
          <span>{{
              scope.row.runMode === '1' ? '启用' : '禁用'
            }}</span>
        </template>

        <template #expand="scope">
          <el-tabs
            v-model="activeTab"
            style="width:95%;margin-left:2.5%;"
            @tab-click="handleTabChange"
          >
            <el-tab-pane label="运行记录" name="tab1"></el-tab-pane>
            <el-tab-pane label="执行日志" name="tab2"></el-tab-pane>
<!--            <el-tab-pane label="调度节点" name="tab3"></el-tab-pane>-->
          </el-tabs>

          <div style="padding: 0 30px">
            <Table v-if="activeTab === 'tab1'" :tab="activeTab" :row="scope.row" @changeTab="handleChangeTab" />
            <div v-else-if="activeTab === 'tab2'">
              <el-tabs
                v-model="editableTabsValue"
                type="card"
                editable
                @edit="handleTabsEdit"
              >
                <el-tab-pane
                  v-for="item in editableTabs"
                  :key="item.name"
                  :label="item.title"
                  :name="item.name"
                >
                  <div v-html="item.content"></div>
                </el-tab-pane>
              </el-tabs>
            </div>
            <div v-else-if="activeTab === 'tab3'"></div>
          </div>
        </template>
    </avue-crud>


    <drag-dialog v-model="addVisible" width="600px" :title="form.ktrTaskId?'编辑':'新增'">
        <el-form :model="form" labelWidth="120px" label-suffix="：" label-width="120px">
            <!-- 转换任务名称 -->
            <el-form-item label="流程名称" prop="ktrTaskName">
              <el-input v-model="form.ktrTaskName" placeholder="请输入转换任务名称"></el-input>
            </el-form-item>
            <!-- 转换任务编码 -->
            <el-form-item label="流程编码" prop="ktrTaskCode">
                <el-input v-model="form.ktrTaskCode" placeholder="请输入转换任务编码"></el-input>
            </el-form-item>


            <el-form-item label="任务类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择任务类型" :disabled="form.ktrTaskId">
                    <el-option value="1" label="离线任务"></el-option>
                    <el-option value="2" label="实时任务"></el-option>
                </el-select>
            </el-form-item>

            <!-- 运行方式 -->
            <el-form-item label="运行方式" prop="runMode">
                <el-select v-model="form.runMode" placeholder="请选择运行方式">
                    <el-option value="1" label="启用"></el-option>
                    <el-option value="2" label="禁用"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item v-if="form.type === '1'" label="调度策略" prop="jobInfoDTO.jobCron">
                <el-popover :visible="cronPopover" width="600px" trigger="click">
                    <cron-editor
                        @cron-change="changeCron"
                        @close="cronPopover = false"
                        :data="form.jobInfoDTO.jobCron"
                        i18n="cn"
                    />
                    <template #reference>
                        <el-input
                            v-model="form.jobInfoDTO.jobCron"
                            placeholder="请输入定时策略"
                            readonly
                            @click="cronPopover = true"
                        >
                          <template #append><i class="el-icon-edit"></i></template>
                        </el-input>
                    </template>
                </el-popover>
            </el-form-item>

            <el-form-item label="路由策略" prop="executorRouteStrategy">
                <dict-selector
                    :dictData="jobExecutorRouteStrategyOptions"
                    v-model="form.jobInfoDTO.executorRouteStrategy"
                    :value="form.jobInfoDTO.executorRouteStrategy"
                    @change="(val) => (form.jobInfoDTO.executorRouteStrategy = val)"
                    style="width: 100%"
                    :clearable="false"
                    :defaultSelectIndex="executorRouteStrategySelectIndex"
                />
            </el-form-item>

            <el-form-item label="阻塞策略" prop="executorBlockStrategy">
                <dict-selector
                    :dictData="jobExecutorBlockStrategyOptions"
                    v-model="form.jobInfoDTO.executorBlockStrategy"
                    :value="form.jobInfoDTO.executorBlockStrategy"
                    @change="(val) => (form.jobInfoDTO.executorBlockStrategy = val)"
                    style="width: 100%"
                    :clearable="false"
                    :defaultSelectIndex="executorBlockStrategySelectIndex"
                />
            </el-form-item>
            <el-form-item label="执行器" prop="jobGroup">
                <dict-selector
                    dictType="job_groups"
                    v-model="form.jobInfoDTO.jobGroup"
                    @change="(val) => (form.jobInfoDTO.jobGroup = val)"
                    style="width: 240px"
                />
            </el-form-item>


            <!-- 备注描述 -->
            <el-form-item label="备注描述" prop="remark">
                <el-input type="textarea" v-model="form.remark" placeholder="这是一条备注的弹窗"></el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="onSubmit">提交</el-button>
                <el-button @click="onCancel">取消</el-button>
            </el-form-item>
        </el-form>
    </drag-dialog>

    <drag-dialog
        v-el-drag-dialog
        :title="viewData.title"
        :close-on-click-modal="false"
        v-model="viewData.open"
        v-if="viewData.open"
        width="90%"
        min-width="800px"
        append-to-body
    >
        <log-dom :viewData="viewData"/>
    </drag-dialog>

</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage} from 'element-plus';
import {getDicts} from '@base/api/base/dict/data'

import {intServiceStore} from '@data/store/index';
import {storeToRefs} from 'pinia';
import {useRouter} from 'vue-router'

const {push} = useRouter()
const intCount = intServiceStore();
const {flowId} = storeToRefs(intCount);
import {search, insert, deleteById, updateById, selectByIdV2, selectById, run} from "@data/api/data/dataDevelopment";
import {getExecutorRouteStrategy, getExecutorBlockStrategy, start, stop, trigger } from '@job/api/job/info'
import {CronEditor} from '@/components/CronEditor'
import {debounce} from "lodash-es";
import TextButton from "@/components/Zmids/Buttons/TextButton.vue";
import logDom from "@/platform/job/views/job/log/index.vue";
import Table from "./components/Table.vue";

const pageSearch = reactive({
    total: 0, // 总页数
    currentPage: 1, // 当前页数
    pageSize: 10 // 每页显示多少条
});
const viewData = reactive({
    open: false,
    title: '调度日志查看',
    jobId: ''
})

const triggerMsg = ref('')
const tableData = ref([]);
const statusOptions = ref([]);
const addVisible = ref(false);
const form = ref({
    ktrTaskCode: '',
    ktrTaskName: '',
    type: '1',
    status: '1',
    cateId: '1',
    cateName: '测试分类',
    runMode: '1',
    remark: '',
    jobInfoDTO: {
        jobGroup: '',
        executorRouteStrategy: '',
        executorBlockStrategy: '',
        jobCron: '',
        triggerStatus: '',
        triggerLastTime: '',
        triggerNextTime: '',
    }
})

const expandRowKeys = ref([]);

const editableTabsValue = ref('2')
const editableTabs = ref([])

const option = ref({
    border: true,
    index: true,
    indexLabel: '序号',
    indexWidth: 70,
    stripe: true,
    selection: true,
    expand: true,
    addBtn: false,
    editBtn: false,
    delBtn: false,
    expandRowKeys: expandRowKeys.value,
    rowKey: 'ktrJsonId',
    column: [
        //{label: '分类名称', prop: 'cateName'},
        {label: '任务名称', prop: 'ktrTaskName'},
        {label: '任务编码', prop: 'ktrTaskCode'},
        {label: '任务类型', prop: 'type'},
        // {label: '最后修改', prop: 'lastTime'},
        {label: '运行方式', prop: 'runMode', slot: true},
        {label: '状态', prop: 'status', slot: true},
        {label: '备注', prop: 'remark'},
        {label: '更新时间', prop: 'updateTime'},

        // {label: '调试', prop: 'log'},
    ],
});


const tabOption = reactive({
    column: [{
        label: '运行记录',
        prop: 'tab1',
    }, {
        label: '执行日志',
        prop: 'tab2',
    },
    //   {
    //     label: '调度节点',
    //     prop: 'tab3',
    // }
    ]
});

const cronPopover = ref(false);
const changeCron = (val) => {
    form.value.jobInfoDTO.jobCron = val
};

const jobExecutorRouteStrategyOptions = ref([]);
const jobExecutorBlockStrategyOptions = ref([]);
const executorRouteStrategySelectIndex = ref(0);
const executorBlockStrategySelectIndex = ref(0);

// 获取路由策略列表
const doGetExecutorRouteStrategy = debounce(() => {
    getExecutorRouteStrategy().then((response) => {
        jobExecutorRouteStrategyOptions.value = response.data
    })
});
const doGetExecutorBlockStrategy = debounce( () => {
    getExecutorBlockStrategy().then((response) => {
      jobExecutorBlockStrategyOptions.value = response.data
    })
});

const activeTab = ref('tab1');
const type = ref({});
const tab = ref('tab1');

const handleTabChange = (tab) => {
  activeTab.value = tab.props.name;
    // type.value = column;
    // tab.value = column.prop;
};

// const rowClick = (row) => {
//     console.log(row);
//     type.value = option.column[0];
//
// };

onMounted(() => {
    type.value = tabOption.column[0];
    getDicts('job_trigger_status').then((response) => {
        statusOptions.value = response.data
        // statusOptions.value = response.data.map(item => ({
        //     ...item,
        //     dictValue: item.dictValue === 'Y' ? '1' : '0' // 映射值转换
        // }))
        console.log('状态字典:', statusOptions.value)

    })
    getList();
    doGetExecutorRouteStrategy();
    doGetExecutorBlockStrategy();
    // getDicts('job_groups').then(response => {
    //     form.jobGroups = response.data.map(item => ({
    //         label: item.dictLabel,
    //         value: item.dictValue
    //     }));
    // });
});

const getList = async () => {
    const res = await search({
        pageNum: pageSearch.currentPage,
        pageSize: pageSearch.pageSize,
        orderBy: 'update_time',
        sortDirect: 'DESC'
    });
    tableData.value = res.data.list;
    console.log(tableData.value)
    pageSearch.total = res.data.total;

}

const sizeChange = (pageSize) => {
    pageSearch.pageSize = pageSize;
    getList();

}
const currentChange = (current) => {
    pageSearch.currentPage = current;
    getList();

}
const refreshChange = () => {
    getList();
}

// 展开行
const expandChanges = (row, expandList) => {
  // expandRowKeys.value = expandList.map(item => item.ktrJsonId);
  const currentKey = row.ktrJsonId;
  if (expandList.includes(currentKey)) {
    expandRowKeys.value = [];
  } else {
    expandRowKeys.value = [currentKey];
  }
}

const handleAdd = () => {
    // intCount.setFlowId('101')
    // push({path: '/trans/design/' + flowId.value})
    form.value = {
        ktrTaskCode: '',
        ktrTaskName: '',
        type: '1',
        status: '1',
        cateId: '1',
        cateName: '测试分类',
        runMode: '1',
        remark: '',
        jobInfoDTO: { // 新增初始化结构
            triggerStatus: 0,
            jobCron: '',
            executorRouteStrategy: '',
            executorBlockStrategy: '',
            jobGroup: ''
        }
    };
    addVisible.value = true;
};

const handleMore = ((command, row) => {
    if(row.runMode === '2')
    {
        ElMessage.error('此任务已禁用')
        return
    }
    if (command === 'start') {
        // row.status = '1';
        doStart(row)
    }
    if (command === 'stop') {
        // row.status = 'N';
        doStop(row)
    }
    if (command === 'trigger') {
        showTrigger(row)
    }
    if (command === 'triggerStart') {
        triggerStart(row)
    }
    if (command === 'triggerStop') {
        triggerStop(row)
    }
})

const doStart = debounce((row) => {
    start(row.jobInfoDTO.id).then((response) => {
        ElMessage.info('启动成功')
        setTimeout(() => {  // 添加1秒延时
            getList()
        }, 1000)
    })
})
const doStop = debounce((row) => {
    stop(row.jobInfoDTO.id).then((response) => {
        ElMessage.info('停止成功')
        setTimeout(() => {  // 添加1秒延时
            getList()
        }, 1000)
    })
})
const showTrigger = debounce((row) => {
    const obj = {
        id: row.jobInfoDTO.id,
        executorParam: row.jobInfoDTO.executorParam,
    }
    trigger(obj).then((response) => {
        ElMessage.success('执行成功');
        setTimeout(() => {  // 添加1秒延时
            getList()
        }, 1000)
    })
})
const triggerStart = (row) => {
    const obj = {
        id: row.jobInfoDTO.id,
        status: 'start',
        executorParam: row.jobInfoDTO.executorParam,
    }
    trigger(obj).then((response) => {
        ElMessage.success('启动成功');
        setTimeout(() => {  // 添加1秒延时
            getList()
        }, 1000)
    })
}
const triggerStop = (row) => {
    const obj = {
        id: row.jobInfoDTO.id,
        status: 'stop',
        executorParam: row.jobInfoDTO.executorParam,
        // executorParam: `{"ktrJsonId":"${row.ktrJsonId.toString()}","status":"stop"}`,
    }
    trigger(obj).then((response) => {
        ElMessage.success('停止成功');
        setTimeout(() => {  // 添加1秒延时
            getList()
        }, 1000)
    })
}

const onSubmit = async () => {
    let fun = form.value.ktrTaskId ? updateById : insert;
    const res = await fun(form.value);
    ElMessage.success('新增成功');
    addVisible.value = false;

    getList()
};

const onCancel = () => {
    addVisible.value = false;
};


const handleUpdate = (row) => {
    console.log(row);
    form.value = row;

    addVisible.value = true;
};

const handleDelete = (row) => {
    console.log(row);
    deleteById(row.ktrTaskId).then((res) => {
        ElMessage.success('删除成功');
        getList();
    });
};

const handleFlow = (row) => {
    selectByIdV2(row.ktrTaskId).then((res) => {
        // console.log(res);
        let { ktrTaskId, ktrJsonId, type, ktrTaskName } = res.data;
        push({path: `/transDesign`, query: {ktrTaskId, ktrJsonId, type, ktrTaskName}})
    });
    //
};

const handleView = (scope, row) => {
    viewData.jobId = scope.row.jobInfoDTO?.id;
    viewData.open = true;
};

const handleViewTab = (scope) => {
  activeTab.value = 'tab2';
  const tabName = `tab-${scope.row.id}-${Date.now()}`;
  editableTabs.value.push({
    title: scope.row.name,
    name: tabName,
    content: scope.row.triggerMsg
  });
  editableTabsValue.value = tabName;
}

const handleChangeTab = (data) => {
  activeTab.value = 'tab2';
  handleViewTab({ row: data.row });
}

const handleTabsEdit = (targetName, action) => {
  if (action === 'add') {
    const newTabName = `tab-new-${Date.now()}`
    editableTabs.value.push({
      title: '新标签页',
      name: newTabName,
      content: ''
    })
    editableTabsValue.value = newTabName
  } else if (action === 'remove') {
    const tabs = editableTabs.value
    let activeName = editableTabsValue.value
    if (activeName === targetName) {
      tabs.forEach((tab, index) => {
        if (tab.name === targetName) {
          const nextTab = tabs[index + 1] || tabs[index - 1]
          if (nextTab) {
            activeName = nextTab.name
          }
        }
      })
    }
    editableTabsValue.value = activeName
    editableTabs.value = tabs.filter((tab) => tab.name !== targetName)
  }
}



</script>
<style lang="scss">
.avue-crud__pagination {
    padding-top: 0px !important;
    margin-right: 30px !important;

    .el-card__body {
        padding-top: 0px !important;
    }
}
</style>
<style scoped lang="scss">
::v-deep .avue-crud .el-table .el-form-item__label {
  position: static !important;
}
::v-deep .el-collapse-item__content {
  margin: 8px 0 15px;
}
</style>